package com.yzc.snow;

import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicLong;

@Component // 标记为 Spring Bean
public class SnowflakeIdUtil {
    // 起始时间戳（2020-01-01）
    private final long epoch = 1577836800000L;

    // 机器ID的位数
    private final long machineIdBits = 10L;

    // 序列号的位数
    private final long sequenceBits = 12L;

    // 最大机器ID（1023）
    private final long maxMachineId = ~(-1L << machineIdBits);

    // 最大序列号（4095）
    private final long maxSequence = ~(-1L << sequenceBits);

    // 机器ID左移位数
    private final long machineIdShift = sequenceBits;

    // 时间戳左移位数
    private final long timestampShift = sequenceBits + machineIdBits;

    // 机器ID
    private long machineId;

    // 序列号
    private final AtomicLong sequence = new AtomicLong(0L);

    // 上次生成ID的时间戳
    private long lastTimestamp = -1L;

    /**
     * 构造函数
     *
     *  machineId 机器ID（0 <= machineId <= maxMachineId）
     */
    public SnowflakeIdUtil() {
        this.machineId = 0;
    }

    /**
     * 设置机器ID
     *
     * @param machineId 机器ID（0 <= machineId <= maxMachineId）
     */
    public void setMachineId(long machineId) {
        if (machineId < 0 || machineId > maxMachineId) {
            throw new IllegalArgumentException("Machine ID must be between 0 and " + maxMachineId);
        }
        this.machineId = machineId;
    }

    /**
     * 生成下一个ID
     *
     * @return 全局唯一ID
     */
    public synchronized long nextId() {
        long timestamp = currentTimestamp();

        // 处理时钟回拨
        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            if (offset <= 5) { // 允许回拨5毫秒
                try {
                    Thread.sleep(offset); // 等待时钟恢复
                    timestamp = currentTimestamp();
                } catch (InterruptedException e) {
                    throw new RuntimeException("时钟倒转，拒绝生成ID");
                }
            } else {
                throw new RuntimeException("时钟倒转，拒绝生成ID");
            }
        }

        if (timestamp == lastTimestamp) {
            sequence.set((sequence.get() + 1) & maxSequence);
            if (sequence.get() == 0) {
                timestamp = waitForNextMillis(lastTimestamp);
            }
        } else {
            sequence.set(0L);
        }

        lastTimestamp = timestamp;

        return ((timestamp - epoch) << timestampShift) |
                (machineId << machineIdShift) |
                sequence.get();
    }

    /**
     * 获取当前时间戳（毫秒）
     *
     * @return 当前时间戳
     */
    private long currentTimestamp() {
        return System.currentTimeMillis();
    }

    /**
     * 等待下一毫秒
     *
     * @param lastTimestamp 上次生成ID的时间戳
     * @return 下一毫秒的时间戳
     */
    private long waitForNextMillis(long lastTimestamp) {
        long timestamp = currentTimestamp();
        while (timestamp <= lastTimestamp) {
            timestamp = currentTimestamp();
        }
        return timestamp;
    }
}